import React, { Component, Fragment } from 'react';
import _ from 'lodash';
import router from 'umi/router';
import {
  Form,
  Input,
  Select,
  Button,
  Row,
  Col,
  message,
  Card,
  Modal,
  Checkbox
} from 'antd';
import { connect } from 'dva';
import isEmpty from 'lodash/isEmpty';
import { stringify } from 'querystring';
import { SERVICE_STATUS } from '@/Constants';
import { maxLength } from '@/utils/form';
import api from '@/api';
import { NAME_RULE, CODE_RULE } from '@/Constants/rules';
import CusInputNumber from '@/components/CusInputNumber';
const FormItem = Form.Item;
const { Option } = Select;

@connect(({ base, currency, price, product, loading }) => ({
  productTags: base.productTags,
  productBrands: base.productBrands,
  timeUnits: base.timeUnits,
  cargoTypes: base.cargoTypes,
  currentProduct: product.currentProduct,
  productGroups: product.productGroups,
  loading: loading.effects['product/fetchCurrent'],
  creating: loading.effects['product/add'],
  updating: loading.effects['product/update'],
  unlockLoading: loading.effects['product/start'],
  lockLoading: loading.effects['product/stop'],
}))
@Form.create()
class BaseView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: 'add',
      uploading: false,
      productDefaultPic: []
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'product/fetchGroups' });
    dispatch({ type: 'base/fetchCargoTypes' });
    dispatch({ type: 'base/fetchTimeUnits' });
    dispatch({ type: 'base/fetchProductTags' });
    dispatch({ type: 'base/fetchProductBrands' });
    dispatch({ type: 'product/queryProductDefaultPic' }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({ productDefaultPic: data })
      }
    })
  }

  componentWillReceiveProps(nextProps) {
    const { mode } = this.state;
    if (!isEmpty(nextProps.currentProduct) && mode === 'add') {
      this.setState({ mode: 'view' });
    }
  }

  handleSave = () => {
    const { dispatch, form, productBrands, creating } = this.props;
    if (creating) return
    const { productDefaultPic } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let payload = {
        ...fieldsValue,
        // brand: productBrands.filter(item => item.name === fieldsValue.tagNameList[0])[0].code,
        // tagNameList: fieldsValue.tagNameList.filter((item, index) => index !== 0),
        // estimatedTime: fieldsValue.estimatedTime.estimatedTime,
        // estimatedUnit: fieldsValue.estimatedTime.estimatedUnit,
        // weightLimitMin: fieldsValue.weightRange.start,
        // weightLimitMax: fieldsValue.weightRange.end,
      };
      if (_.isEmpty(fieldsValue.imageFile)) {
        let img = productDefaultPic.filter(item => item.code === payload.brand)[0]
        payload.imageFile = {
          id: img.imageId,
          name: null,
          originPath: null,
          path: img.image,
          thumbnailPath: null,
          type: null,
        }
      }
      dispatch({
        type: 'product/add',
        payload: {
          data: payload,
        },
      }).then(res => {
        if (res.errorCode === 0) {
          dispatch({
            type: 'product/fetchCurrent',
            payload: {
              pathParams: {
                id: res.data,
              },
            },
          });
          form.resetFields();
          message.success('添加成功');
          let query = {
            productId: res.data,
            backRoute: '/product/manage',
            entry: 'manage',
          };
          router.push(`/product/manage/add/base?${stringify(query)}`);
        }
      });
    });
  };

  handleUpdate = () => {
    const { dispatch, form, currentProduct, productBrands, updating } = this.props;
    if (updating) return
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let payload = {
        ...currentProduct,
        ...fieldsValue,
        // brand: productBrands.filter(item => item.name === fieldsValue.tagNameList[0])[0].code,
        // tagNameList: fieldsValue.tagNameList.filter((item, index) => index !== 0),
        // estimatedTime: fieldsValue.estimatedTime.estimatedTime || 0,
        // estimatedUnit: fieldsValue.estimatedTime.estimatedUnit,
        // weightLimitMin: fieldsValue.weightRange.start || 0,
        // weightLimitMax: fieldsValue.weightRange.end || 0,
      };
      dispatch({
        type: 'product/update',
        payload: {
          pathParams: {
            id: currentProduct.id,
          },
          data: payload,
        },
      }).then(res => {
        if (res.errorCode === 0) {
          dispatch({
            type: 'product/fetchCurrent',
            payload: {
              pathParams: {
                id: currentProduct.id,
              },
            },
          }).then(response => {
            if (response.errorCode === 0) {
              this.setState({ mode: 'view' });
            }
          });
          form.resetFields();
          message.success('更新成功');
        }
      });
    });
  };

  handleAudit = fieldsValue => {
    const { dispatch, currentProduct } = this.props;
    return dispatch({
      type: 'product/audit',
      payload: {
        pathParams: {
          id: currentProduct.id,
        },
        data: fieldsValue,
      },
    }).then(res => {
      if (res.errorCode === 0) {
        message.success('审核成功');
        router.push('/product/audit');
      }
    });
  };

  checkCode = (rule, value = '', callback) => {
    const { mode } = this.state;
    const { currentProduct } = this.props;
    if (value === '') {
      return callback();
    }
    let payload = {
      [rule.field]: value,
    };
    if (mode === 'edit') {
      payload.id = currentProduct.id;
    }
    api.product
      .checkCode({
        queryParams: payload,
      })
      .then(res => {
        if (!res.data) {
          callback(rule.message);
        } else {
          callback();
        }
      });
  };

  handleInput = e => {
    let val = e.target.value;
    val = val.trim();
    val = val.substr(0, 30);
    e.target.value = val;
  };

  validate = (rule, value, callback) => {
    const { start, end } = value;
    if (start >= end) {
      callback(rule.message);
    } else {
      callback();
    }
  };

  handleOnline = () => {
    const { dispatch, unlockLoading, currentProduct } = this.props;
    if (unlockLoading) return
    Modal.confirm({
      title: '启用产品',
      content: '确定启用此产品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'product/start',
          payload: {
            pathParams: {
              id: currentProduct.id,
            },
          },
        }).then(res => {
          if (res.errorCode === 0) {
            dispatch({
              type: 'product/fetchCurrent',
              payload: {
                pathParams: {
                  id: currentProduct.id,
                },
              },
            });
            message.success('启用成功');
          }
        });
      },
    });
  };

  handleOffline = () => {
    const { dispatch, lockLoading, currentProduct } = this.props;
    if (lockLoading) return
    Modal.confirm({
      title: '停用产品',
      content: '确定停用此产品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'product/stop',
          payload: {
            pathParams: {
              id: currentProduct.id,
            },
          },
        }).then(res => {
          if (res.errorCode === 0) {
            dispatch({
              type: 'product/fetchCurrent',
              payload: {
                pathParams: {
                  id: currentProduct.id,
                },
              },
            });
            message.success('停用成功');
          }
        });
      },
    });
  };
  handleTagChange = value => {
    const { productBrands, form } = this.props;
    let brand = value[0];
    if (!productBrands.map(item => item.name).includes(brand)) {
      // 清空这里有问题
      setTimeout(() => {
        form.setFieldsValue({ tagNameList: [] });
      }, 0);
    }
  };
  isProductBrandDisabled = name => {
    const { form } = this.props;
    let selectList = form.getFieldValue('tagNameList');

    // 没有选择品牌的情况下,品牌为可选
    if (!selectList || selectList.length === 0) {
      return false;
    }
    // 当前选中的品牌为可选,其余的不可选
    let brand = selectList[0];
    return brand !== name;
  };
  isProductTagDisabled = name => {
    const { form } = this.props;
    let selectList = form.getFieldValue('tagNameList');
    // 没有选择品牌的情况下,标签不可选
    if (!selectList || selectList.length === 0) {
      return true;
    }
    if (selectList.includes(name)) {
      return false;
    }
    if (selectList.filter((item, index) => index !== 0).length > 1) {
      return true;
    }
  };
  checkTime = (rule, value, callback) => {
    if (!value.estimatedTime) {
      callback('请输入预估时效')
    } else {
      callback();
    }
  }
  handleCheckAll = (e) => {
    const { form: { setFieldsValue }, cargoTypes } = this.props;
    let cargoTypeCodeList = []
    if (e.target.checked) {
      cargoTypeCodeList = cargoTypes.map(item => item.code)
    }
    setFieldsValue({ cargoTypeCodeList })
  }
  renderForm = () => {
    const {
      form: { getFieldDecorator, getFieldsValue },
      cargoTypes,
      currentProduct,
      creating,
      updating,
    } = this.props;
    const { mode } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    return (
      <div>
        <FormItem label="名&#12288;&#12288;称" {...formItemLayout}>
          {getFieldDecorator('name', {
            rules: [
              { required: true, message: '名称不能为空', whitespace: true },
              {
                pattern: NAME_RULE.PATTERN,
                message: NAME_RULE.MESSAGE,
              },
            ],
            initialValue: currentProduct.name,
          })(<Input disabled={mode === 'edit'} style={{ width: 264 }} onInput={e => maxLength(e, 30)} />)}
        </FormItem>
        <FormItem label="编&#12288;&#12288;码" {...formItemLayout}>
          {getFieldDecorator('code', {
            rules: [
              { required: true, message: '编码不能为空', whitespace: true },
              { pattern: CODE_RULE.PATTERN, message: CODE_RULE.MESSAGE },
              { validator: this.checkCode, message: '编码已存在' },
            ],
            validateTrigger: 'onBlur',
            initialValue: currentProduct.code,
          })(
            <Input
              style={{ width: 264 }}
              disabled={mode === 'edit'}
              onInput={e => maxLength(e, 15)}
            />
          )}
        </FormItem>
        {/* <FormItem label="产&ensp;品&ensp;组" {...formItemLayout}>
          {getFieldDecorator('productGroup', {
            rules: [{ required: true, message: '产品组不能为空' }],
            initialValue: currentProduct.productGroup,
          })(
            <Select
              disabled={mode === 'edit'}
              optionFilterProp="children"
              style={{ width: 264 }}
              onInputKeyDown={e => maxLength(e, 30)}
              filterOption={(inputValue, option) => {
                let val = inputValue.trim();
                return option.props.children.includes(val.toUpperCase());
              }}
            >
              {productGroups.map(val => (
                <Option key={val.id} value={val.id}>{`${val.name}`}</Option>
              ))}
            </Select>
          )}
        </FormItem>
        <FormItem label="产品标签" {...formItemLayout} required>
          {getFieldDecorator('tagNameList', {
            rules: [{ required: true, message: '产品标签不能为空' }],
            initialValue: currentProduct.tagNameList
              ? [currentProduct.brandName, ...currentProduct.tagNameList]
              : [currentProduct.brandName].filter(item => item),
          })(
            <Select style={{ width: 264 }} mode="multiple" onChange={this.handleTagChange}>
              <OptGroup label="品牌">
                {productBrands.map((item, index) => (
                  <Option
                    key={index}
                    value={item.name}
                    disabled={this.isProductBrandDisabled(item.name)}
                  >
                    {item.name}
                  </Option>
                ))}
              </OptGroup>
              <OptGroup label="标签">
                {productTags.map((productTag, index) => (
                  <Option
                    key={index}
                    value={productTag.name}
                    disabled={this.isProductTagDisabled(productTag.name)}
                  >
                    {productTag.name}
                  </Option>
                ))}
              </OptGroup>
            </Select>
          )}
        </FormItem> */}
        <FormItem label="货物类型" {...formItemLayout} required>
          {getFieldDecorator('cargoTypeCodeList', {
            rules: [{ required: true, message: '货物类型不能为空' }],
            initialValue: currentProduct.cargoTypeCodeList,
          })(
            <Select style={{ width: 264 }} mode="multiple">
              {cargoTypes.map((cargoType, index) => (
                <Option key={index} value={cargoType.code}>
                  {cargoType.name}
                </Option>
              ))}
            </Select>
          )}
          <Checkbox style={{ marginLeft: 10 }} onChange={this.handleCheckAll}>全选</Checkbox>
        </FormItem>
        {/*<FormItem label="预售天数" {...formItemLayout}>
          {getFieldDecorator('preSaleDays', {
            rules: [
              { required: true, message: '预售天数不能为空', whitespace: true },
            ],
            validateTrigger: 'onBlur',
            initialValue: currentProduct.preSaleDays,
          })(
            <CusInputNumber
              precision={0}
              max={999}
              min={1}
              style={{ width: 264 }}
            />
          )}
        </FormItem>
         <FormItem label="产品主图" {...formItemLayout}>
          {getFieldDecorator('imageFile', {
            rules: [],
            initialValue: imageFile ? imageFile : null,
          })(<ProductPic isUpload={true} productDefaultPic={productDefaultPic} info={info} />)}
        </FormItem>
        <FormItem label="产品介绍" {...formItemLayout}>
          {getFieldDecorator('introduction', {
            rules: [{ required: true, message: '产品介绍不能为空', whitespace: true }],
            initialValue: currentProduct.introduction,
          })(<Input.TextArea style={{ width: 264 }} onInput={e => maxLength(e, 140)} />)}
        </FormItem>
        <FormItem label="预估时效" {...formItemLayout} required>
          {getFieldDecorator('estimatedTime', {
            rules: [
              {
                validator: this.checkTime, message: '请输入预估实效'
              }
            ],
            initialValue: {
              estimatedTime: currentProduct.estimatedTime,
              estimatedUnit: currentProduct.estimatedUnit || 'DAY',
            },
          })(
            <CusInput
              width={264}
              addon={timeUnits}
              label="estimatedTime"
              addonLabel="estimatedUnit"
            />
          )}
        </FormItem>
        <FormItem label="重量限制" {...formItemLayout}>
          {getFieldDecorator('weightRange', {
            rules: [{ validator: Range.validate, message: '下限必须小于上限' }],
            initialValue: {
              start: currentProduct.weightLimitMin,
              end: currentProduct.weightLimitMax,
            },
          })(
            <Range
              precision={3}
              max={99999}
              min={0.001}
              width={200}
              extra={
                <Select defaultValue="kg" style={{ width: '60px', marginLeft: '4px' }}>
                  <Option key="kg" value="kg">
                    kg
                  </Option>
                </Select>
              }
            />
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="受理方式">
          {getFieldDecorator('acceptType', {
            initialValue: currentProduct.acceptType === 0 ? 0 : 1,
          })(
            <Radio.Group>
              <Radio value={1}>人工</Radio>
              <Radio value={0}>自动</Radio>
            </Radio.Group>
          )}
        </FormItem>
        <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
          {getFieldDecorator('description', {
            initialValue: currentProduct.description,
          })(<Input.TextArea style={{ width: 264 }} onInput={e => maxLength(e, 140)} />)}
        </FormItem> */}
        <Row type="flex">
          <Col span={5} />
          {mode == 'add' && (
            <Button
              type="primary"
              style={{ marginLeft: 110 }}
              onClick={this.handleSave}
              loading={creating}
            >
              保存
            </Button>
          )}
          {mode == 'edit' && (
            <Fragment>
              <Button style={{ marginLeft: 50 }} onClick={() => this.setState({ mode: 'view' })}>
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 30 }}
                onClick={this.handleUpdate}
                loading={updating}
              >
                保存
              </Button>
            </Fragment>
          )}
        </Row>
      </div>
    );
  };

  renderView = () => {
    const { currentProduct, unlockLoading, lockLoading } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    return (
      <div style={{ position: 'relative' }}>
        <div style={{ position: 'absolute', right: 20, top: 15, zIndex: 2 }}>
          {(currentProduct.status === SERVICE_STATUS.DRAFT ||
            (!currentProduct.isOnline &&
              currentProduct.status === SERVICE_STATUS.AUDITTED)) && (
              <Button
                type="primary"
                style={{ marginRight: 10 }}
                onClick={() => this.setState({ mode: 'edit' })}
              >
                编辑
            </Button>
            )}
          {
            currentProduct.status === SERVICE_STATUS.AUDITTED &&
            !currentProduct.isOnline && (
              <Button type="primary" loading={unlockLoading} onClick={this.handleOnline}>
                启用
              </Button>
            )}
          {
            currentProduct.status === SERVICE_STATUS.AUDITTED &&
            currentProduct.isOnline && (
              <Button type="primary" loading={lockLoading} onClick={this.handleOffline}>
                停用
              </Button>
            )}
        </div>
        <FormItem label="名&#12288;&#12288;称" {...formItemLayout}>
          {currentProduct.name}
        </FormItem>
        <FormItem label="编&#12288;&#12288;码" {...formItemLayout}>
          {currentProduct.code}
        </FormItem>
        {/* <FormItem label="产&ensp;品&ensp;组" {...formItemLayout}>
          {currentProduct.groupName}
        </FormItem>
        <FormItem label="产品标签" {...formItemLayout}>
          {currentProduct.brandName}{currentProduct.tagNameList.length ? `,${currentProduct.tagNameList}` : ''}
        </FormItem> */}
        <FormItem label="货物类型" {...formItemLayout}>
          {`${currentProduct.cargoTypeNameList}`}
        </FormItem>
        {/* <FormItem label="预售天数" {...formItemLayout}>
          {currentProduct.preSaleDays}
        </FormItem>
        <FormItem label="产品主图" {...formItemLayout} className={styles.uploader}>
          <ProductPic info={info} showResult={false} />
        </FormItem>
        <FormItem label="产品介绍" {...formItemLayout}>
          {currentProduct.introduction}
        </FormItem>
        <FormItem label="预估时效" {...formItemLayout}>
          {currentProduct.estimatedTime}
          {currentProduct.estimatedTime ? currentProduct.estimatedUnitName : ''}
        </FormItem>
        <FormItem label="重量限制" {...formItemLayout}>
          {currentProduct.weightLimitMin}-{currentProduct.weightLimitMax}
          {currentProduct.weightLimitMin ? `(${currentProduct.weightLimitUnitCode})` : ''}
        </FormItem>
        <FormItem label="受理方式" {...formItemLayout}>
          {currentProduct.acceptType == 1 ? '人工' : '自动'}
        </FormItem>
        <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
          {currentProduct.description}
        </FormItem> */}
      </div>
    );
  };

  render() {
    const { mode } = this.state;
    const { loading } = this.props;
    let renderer = null;
    if (mode === 'add' || mode === 'edit') renderer = this.renderForm();
    if (mode === 'view') renderer = this.renderView();
    return (
      <Card bordered={false} loading={loading}>
        {renderer}
      </Card>
    );
  }
}

export default BaseView;
